package utils

import (
	"context"
	"github.com/google/uuid"
	"google.golang.org/grpc/metadata"
)

const (
	RequestIDKey = "x-request-id"
	UserNameKey  = "x-username"
)

// GetRequestID request id from header
func GetRequestID(ctx context.Context) string {
	val := GetHeaderFirst(ctx, RequestIDKey)
	if val == "" {
		return GenerateRequestID()
	}
	return val
}

// GetUserName get username from header
func GetUserName(ctx context.Context) string {
	return GetHeaderFirst(ctx, UserNameKey)
}

// GetHeaderFirst get header value by key
func GetHeaderFirst(ctx context.Context, key string) string {
	if md, ok := metadata.FromIncomingContext(ctx); ok {
		if values := md.Get(key); len(values) > 0 {
			return values[0]
		}
	}
	return ""
}

// GenerateRequestID generate a random requestId
func GenerateRequestID() string {
	return uuid.New().String()
}
